/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package TimeRecording.forms.renderers;

import TimeRecording.widgets.TimeFormatter;
import java.awt.Component;
import java.text.DecimalFormat;
import java.text.ParseException;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;

/**
 *
 * @author cbegg
 */
public class HoursCellRenderer extends DefaultTableCellRenderer {

    private static TimeFormatter hoursAndMinutesFormatter = new TimeFormatter();
    private static DecimalFormat hoursFormatter = new DecimalFormat("0.00");

    private boolean showHoursAndMinutes = true;

    public void showHoursAndMinutes(boolean showHoursAndMinutes) {
        this.showHoursAndMinutes = showHoursAndMinutes;
    }

    public String formatValue(Object value) {

        if (value instanceof Double) {
            if ((Double)value != 0) {
                try {
                    if (showHoursAndMinutes) {
                        return hoursAndMinutesFormatter.valueToString(value);
                    } else {
                        return hoursFormatter.format(value);
                    }
                } catch (ParseException ex) {
                    return "";
                }
            } else {
                return "";
            }
        } else {
            return "";
        }
    }

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value,
            boolean isSelected, boolean hasFocus, int row, int column) {

        value = formatValue(value);

        JLabel component = (JLabel)super.getTableCellRendererComponent(
                table, value, isSelected, hasFocus, row, column);

        component.setHorizontalAlignment(SwingConstants.CENTER);

        return component;
    }
}
